package com.chao.common.util.exception;

import com.alibaba.fastjson.JSONObject;
import com.chao.common.util.RequestUtile;
import com.chao.common.util.reaction.Reaction;
import com.chao.common.util.reaction.ReactionCode;
import com.chao.common.util.reaction.ReactionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice()
public class ExceptionUtile {

    private static long time = 0;

    private static final Logger log = LoggerFactory.getLogger(ExceptionUtile.class);

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Reaction handleException(Exception e) {
        if(e instanceof com.chao.common.util.exception.SysException){
            com.chao.common.util.exception.SysException e1 = (SysException) e;
            log.error("===============业务异常================{}:{}",e1.getCode(),e1.getContent());
            return new ReactionImpl(e1.getCode(), e1.getContent());
        }
        if(System.currentTimeMillis() > time){
            log.error("===============系统异常:{}================",RequestUtile.getIp(),e);
            JSONObject data = new JSONObject();
            data.put("errorType", e.getClass().getName());
            data.put("errorMsg", e.getMessage());
            data.put("errorCustomer",RequestUtile.getCustomer());
//            MqttUtile.sendMessage("saas/error", data); todo
            time = System.currentTimeMillis() + 10 * 1000; // 10秒内只触发一次请求
        }
	    if (e instanceof NullPointerException) {
            return new ReactionImpl(ReactionCode.OTHER,"非法操作,数据不能为空!");
	    }
        return new ReactionImpl(ReactionCode.OTHER,e.getMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Error.class)
    public Reaction handleError(Error e) {
        log.error("异常2222",e);
        return new ReactionImpl(ReactionCode.OTHER,e.getMessage());
    }
}
